package application3.servlet;

import application3.controller.InputController;
import application3.controller.SaveProductController;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 带有验证器的请求调度类
 */
@WebServlet(name = "DispatcherServlet", urlPatterns = {"/product_input3.action","/product_save3.action"})
public class DispatcherServlet extends HttpServlet {
    private void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");

        String uri = request.getRequestURI();
        int lastIndex = uri.indexOf("/");
        String action = uri.substring(lastIndex+1);

        String dispachterUri = null;
        if (action.equals("product_input3.action")){
            InputController inputController = new InputController();
            dispachterUri = inputController.handleRequest(request,response);
        } else if (action.equals("product_save3.action")){
            // 带有验证器的控制层
            SaveProductController saveProductController = new SaveProductController();
            dispachterUri = saveProductController.handleRequest(request,response);
        }

        // 请求调度
        if (dispachterUri != null){
            RequestDispatcher requestDispatcher = request.getRequestDispatcher(dispachterUri);
            requestDispatcher.forward(request,response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       process(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        process(req,resp);
    }
}
